package spindles.gwt.server;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import org.apache.commons.lang.time.DurationFormatUtils;

import spindles.api.domain.Audit;
import spindles.api.util.ApplicationException;
import spindles.gwt.shared.AuditDTO;
import spindles.gwt.shared.ImportManager;

public class ImportServletStub extends StubServlet implements ImportManager{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1258568480280408796L;

	@SuppressWarnings("unchecked")
	public List getAudits() {
		List<Audit> audits = new ArrayList<Audit>();
		Audit a = new Audit();
		a.setFilename("kopsaftis1.txt");
		a.setEegDuration(304);
		a.setFileSize(22);
		a.setImportStartTime(new Date());
		a.setImportEndTime(new Date());
		a.setRecordsCount(77853);
		a.setSamplingRate(256);
		
		Audit a1 = new Audit();
		a1.setFilename("kopsaftis2.txt");
		a1.setEegDuration(304);
		a1.setFileSize(22);
		a1.setImportStartTime(new Date());
		a1.setImportEndTime(new Date());
		a1.setRecordsCount(77853);
		a1.setSamplingRate(256);
		
		audits.add(a);
		audits.add(a1);
		
		List result = new ArrayList();
		
		for(Audit aud : audits){
			AuditDTO dto = (AuditDTO)ServletUtil.map(aud, AuditDTO.class);
			dto.setEegDuration(DurationFormatUtils.formatDurationHMS(304 * 1000));
			dto.setImportDuration(DurationFormatUtils.formatDurationHMS(300000));
			result.add(dto);
		}		
		
		return result;
	}

	@SuppressWarnings("unchecked")
	public List getRecentAudits(int numberOfAudits) {
		List audits = getAudits();
		List result = new ArrayList();
		for(int i = 0; i < numberOfAudits; i++){
			result.add(audits.get(i));
		}
		
		return result;
	}

	public void importSessionPartData(String filename, String channel,
			boolean allowDuplicatePerson) {
		if(isImporting()){
			throw new ApplicationException("Cannot run more than one import operation.");
		}
		getServletContext().setAttribute("imp.busy", true);
		
		Executor e = Executors.newSingleThreadExecutor();
		e.execute(getRunnable());
		
	}

	public boolean isImporting() {
		
		Boolean isImporting = (Boolean)getServletContext().getAttribute("imp.busy");
		
		return isImporting != null && isImporting;
	}
	
	private Runnable getRunnable() {
		return new Runnable() {

			public void run() {
				try {
					Thread.sleep(1000 * 60);
				} catch (InterruptedException e) {
					throw new ApplicationException(e);
				} finally {
					getServletContext().setAttribute("imp.busy", false);
				}

			}

		};
	}

}
